package com.qyl.deguru.controller.customer;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.qyl.deguru.common.PageConstant;
import com.qyl.deguru.dto.Comment;
import com.qyl.deguru.dto.Shop;
import com.qyl.deguru.dto.User;
import com.qyl.deguru.service.CommentService;
import com.qyl.deguru.service.ShopService;
import com.qyl.deguru.service.impl.CommentServiceImple;
import com.qyl.deguru.service.impl.ShopServiceImple;
import com.qyl.deguru.utils.UploadUtil;

/**
 * 评价控制类
 * */
@Controller
@RequestMapping("/customer/comment")
public class CommentController {
	ShopService shopService=new ShopServiceImple();
	CommentService commentService=new CommentServiceImple();

	//上传图片
	@RequestMapping("/uploadpic")
	@ResponseBody
	public Map<String, String> uploadpic(@RequestParam("myfile") MultipartFile file,
			Comment comment,ModelMap modelmap) throws IllegalStateException, IOException{
		//图片
		Map<String, String> map=new HashMap<String, String>();
		try{
			String image=UploadUtil.loadFile(file);
			comment.setImage(image);
			map.put("image", image);
			modelmap.addAttribute("image", image);
			map.put("status", "success");
		}catch(Exception e){
			System.out.println("图片上传失败");
		}
		return map;
	}
	//添加评论
	@RequestMapping("/addComment")
	public String addComment(Comment comment,ModelMap modelMap,HttpSession session,RedirectAttributes redirectValue) {
		//设置创建时间
		comment.setCreate_date(new Date());
		//设置创建人
		User user=(User) session.getAttribute(PageConstant.SESSION_USER);
		comment.setUser(user);
		System.out.println(comment);
		int count=commentService.addComment(comment);
		if(count>0) {
			modelMap.put(PageConstant.TIP, "插入评论成功");
		}else {
			modelMap.put(PageConstant.TIP, "插入评论失败");
		}
		Integer goodId = comment.getShop().getId();
		
		redirectValue.addAttribute("cid", goodId);
		redirectValue.addAttribute(PageConstant.TIP, modelMap.get(PageConstant.TIP));
		System.out.println(comment+"0000");
		return "redirect:toComment";
	}
	@RequestMapping("/toComment")
	public String toComment(ModelMap modelMap,Integer cid,String tip){
		Shop shops=shopService.getShopById(cid);
		modelMap.addAttribute("shops", shops);
		modelMap.addAttribute("cid", cid);
		modelMap.put(PageConstant.TIP, tip);
		return "comments";
	}
}


